package com.atguigu.jucdemo.test;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SaleTicket {
    private int num = 50;
    //默认非公平，加上参数true为公平锁
    private Lock l = new ReentrantLock();

    public void sale() {
        l.lock();
        try {
            if(num>0){
                System.out.println(Thread.currentThread().getName() + "取走了第" + (num--) + "张票" + "还剩余" + num + "张");
            }
        } finally {
            l.unlock();
        }
    }
}

public class SaleTicketDemo01 {
    public static void main(String[] args) {
   SaleTicket ticket = new SaleTicket();
        /*new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "张三").start();
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "赵四").start();
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "王五").start();*/

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            for (int i = 1; i <= 50; i++) {
                threadPool.execute(()->{
                    ticket.sale();
                });
            }
        } finally {
            threadPool.shutdown();
        }
    }
}
